package com.woyou.ui.activity;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.json.JSONException;
import org.json.JSONObject;

import retrofit.RetrofitError;
import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.citaq.ideliver.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.woyou.Constant;
import com.woyou.bean.CodeResult;
import com.woyou.bean.Coupon;
import com.woyou.bean.Info;
import com.woyou.bean.ShopItem;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.MD5Req;
import com.woyou.bean.rpc.PwdCheckReq;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.fragment.ShopsFragment_;
import com.woyou.utils.Dialog;
import com.woyou.utils.Utils;

/**
 * 使用优惠券
 * 
 * @author shenzhou 2015年1月8日
 */
@EActivity(R.layout.fm_coupon)
public class UseCouPonActivity extends BaseActivity {

	@ViewById
	RelativeLayout myback;
	@ViewById
	TextView head_title;
	@ViewById(R.id.coupon_webview)
	WebView mWeb;
	@ViewById(R.id.hintView)
	ErrorHintView hintView;

	private ShopItem shopItem;
	private UserInfo userInfo;
	private Dialog dialog = new Dialog();

	/** 显示优惠券列表 **/
	private int VIEW_COUPON = 1;
	/** 显示断网 **/
	private int VIEW_WIFIFAILUER = 2;
	/** 显示加载数据失败 **/
	private int VIEW_LOADFAILURE = 3;
	/** 显示加载中 **/
	private int VIEW_LOADING = 4;
	/** 显示请求超时 **/
	private int VIEW_OUTTIME = 5;

	@AfterViews
	public void init() {
		if (hasInfo()) {
			Object obj = mInfo.getData();
			if (obj instanceof ShopItem) {
				shopItem = (ShopItem) obj;
			}
		}
		head_title.setText("选择优惠券");
		initView();
	}

	@Click({ R.id.myback })
	void loginOnClick(View view) {
		switch (view.getId()) {
		case R.id.myback:
			// 退出设置界面
			closeActivity4Result(1, null);
			break;
		}
	}

	class Params {
		public String uId;
		public String sId;
		public String pwd;
		public String lat;
		public String lng;
		public String cityName;
		public float totalPrice;
	}

	public void initView() {
		showViewById(VIEW_LOADING);
		String url = "http://" + Constant.WEB_SERVER
				+ "/ResultMyCoupon2/getCoupon.php";
		userInfo = mUserModel.getUserInfo();
		Params params = new Params();
		params.uId = userInfo.getuId();
		params.pwd = userInfo.getPwd();
		params.sId = shopItem.sId;
		params.lat = mBaiduLocationService.getLastLocation().getLatitude() + "";
		params.lng = mBaiduLocationService.getLastLocation().getLongitude()
				+ "";
		params.cityName = mBaiduLocationService.getLastLocation().getCity();
		params.totalPrice = mShoppingCarModel.getBaseCost();

		MD5Req<Params> req = new MD5Req<Params>(params);
		try {
			url = Utils.getWebUrl(url, req);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		initWebView(url);
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView(String url) {
		// 如果访问的页面中有Javascript，则webview必须设置支持Javascript
		mWeb.getSettings().setJavaScriptEnabled(true);
		mWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		// 触摸焦点起作用
		mWeb.requestFocus();
		// 取消滚动条
		mWeb.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		// 设置WevView要显示的网页：
		mWeb.loadUrl(url);
		// 设置不可缩放
		mWeb.getSettings().setSupportZoom(false);
		mWeb.getSettings().setBuiltInZoomControls(false);

		mWeb.setWebViewClient(new MyWebViewClient());
		mWeb.setWebChromeClient(new WebChromeClient());
		mWeb.addJavascriptInterface(this, "ideliver");

	}

	class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (!TextUtils.isEmpty(url)) {
				mWeb.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			showViewById(VIEW_COUPON);

			String title = view.getTitle();
			if (TextUtils.isEmpty(title)) {
				return;
			}

			if (!title.contains("ideliver")) {
				if (!NetWorkCenter.isNetworkConnected(mContext)) {
					showViewById(VIEW_WIFIFAILUER);
				} else {
					showViewById(VIEW_LOADFAILURE);
				}

			}
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			if (!NetWorkCenter.isNetworkConnected(mContext)) {
				showViewById(VIEW_WIFIFAILUER);
			} else {
				showViewById(VIEW_OUTTIME);
			}
		}
	}

	/**
	 * JS端发送消息到android
	 * 
	 * @param message
	 */
	@SuppressWarnings("rawtypes")
	public void messageFromJS(String message) {
		// Toast.makeText(mContext, message, 1).show();
		try {
			JSONObject msg = new JSONObject(message);
			String type = msg.getString("messageType");
			if ("selectCoupon".equals(type)) {
				String list = msg.getString("params");
				Gson gson = new Gson();
				List<Coupon> coupons = gson.fromJson(list,
						new TypeToken<List<Coupon>>() {
						}.getType());
				if (coupons != null && coupons.size() > 0) {
					// 使用优惠券
					Info<List<Coupon>> info = new Info<List<Coupon>>();
					info.setData(coupons);
					info.setOrigin(UseCouPonActivity_.class);
					closeActivity4Result(1, info);
					
				} else {
					Toast.makeText(mContext, "使用优惠券失败!", Toast.LENGTH_SHORT)
							.show();
				}

			} else if ("tryAgain".equals(type)) {
				showProgressDialog();
				mBaiduLocationService.startLocation();

			} else if ("browseShops".equals(type)) {
				// 浏览店铺
				Info<Class> info = new Info<Class>();
				info.setData(ShopsFragment_.class);
				info.setOrigin(UseCouPonActivity_.class);
				openActivity(HomeActivity_.class, info);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		} finally {
			dismissProgressDialog();
		}
	}
	
	
	private PwdCheckReq pwdCheckReq = new PwdCheckReq();

	/**
	 * 优惠券验证密码
	 */
	@SuppressWarnings("rawtypes")
	@Background
	void couponPwdCheck() {
		if (!NetWorkCenter.isNetworkConnected(mContext)) {
			showViewById(VIEW_WIFIFAILUER);
			return;
		}
		userInfo = mUserModel.getUserInfo();
		pwdCheckReq.setuId(userInfo.getuId());
		pwdCheckReq.setPwd(userInfo.getPwd());
		try {
			CodeResult result = mUserModel.pwdCheck(pwdCheckReq);
			if (result != null && result.getCode() == -1) {
				dialog.LoginToast(mContext, "您的账号已在其他地方登录，请重新登录",
						UseCouPonActivity_.class);

			} else if (result != null && result.getCode() == 1) {
				initView();
			} else if (result != null && result.getCode() == -2) {
				showViewById(VIEW_LOADFAILURE);
			}
		} catch (

		RetrofitError e)

		{
			switch (e.getKind()) {
			case HTTP:
				showViewById(VIEW_OUTTIME);
				return;
			case CONVERSION:
				showViewById(VIEW_LOADFAILURE);
				return;
			case NETWORK:
				showViewById(VIEW_OUTTIME);
				return;
			case UNEXPECTED:
				showViewById(VIEW_LOADFAILURE);
				return;
			}
		}

	}

	/**
	 * 显示优惠券列表：1 显示断网：2 显示加载数据失败：3 显示加载中：4 显示请求超时：5
	 */
	@UiThread
	void showViewById(int i) {
		hintView.setVisibility(View.GONE);
		mWeb.setVisibility(View.GONE);
		switch (i) {
		case 1:
			hintView.hideLoading();
			mWeb.setVisibility(View.VISIBLE);
			break;
		case 2:
			hintView.hideLoading();
			hintView.netError(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					initView();
				}
			});
			break;
		case 3:
			hintView.hideLoading();
			hintView.loadFailure(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					initView();
				}
			});
			break;
		case 4:
			hintView.loadingData();
			break;
		case 5:
			hintView.hideLoading();
			hintView.timeOut(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					initView();
				}
			});
			break;
		}
	}

	@Override
	public boolean backOperate() {
		return false;
	}

}
